package cn.edu.hitwh.kanlema.service.impl;

import cn.edu.hitwh.kanlema.dto.UserDTO;
import cn.edu.hitwh.kanlema.entity.Follow;
import cn.edu.hitwh.kanlema.mapper.FollowMapper;
import cn.edu.hitwh.kanlema.service.IFollowService;
import cn.edu.hitwh.kanlema.service.IUserService;
import cn.edu.hitwh.kanlema.util.UserHolder;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author vvcoder
 * @since 2025-8-18
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Autowired
    private IUserService userService;

    @Override
    public boolean follow(Long id, Boolean follow) {
        Long userId = UserHolder.getUser().getId();
        if (Boolean.TRUE.equals(follow)) {
            // 关注
            Follow followEntity = new Follow();
            followEntity.setUserId(userId);
            followEntity.setFollowUserId(id);
            return save(followEntity);
        } else {
            // 取消关注
            return remove(new LambdaQueryWrapper<Follow>()
                    .eq(Follow::getUserId, userId)
                    .eq(Follow::getFollowUserId, id));
        }
    }

    @Override
    public boolean isFollow(Long id) {
        Long userId = UserHolder.getUser().getId();
        return lambdaQuery()
                .eq(Follow::getUserId, userId)
                .eq(Follow::getFollowUserId, id)
                .count() > 0;
    }

    @Override
    public List<UserDTO> commonFollow(Long id) {
        Long userId = UserHolder.getUser().getId();
        List<Long> commonFollowIds = baseMapper.commonFollow(userId, id);
        if (commonFollowIds.isEmpty()) {
            return Collections.emptyList();
        }
        return commonFollowIds.stream()
                .map(userService::getById)
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
    }
}
